package com.linxcool.media;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.linxcool.util.BitmapMemoryCache;
import com.linxcool.util.ImageUtil;
import com.linxcool.util.R;

/**
 * 一个目录的相册适配器
 * @author 胡昌海(linxcool.hu)
 */
public class ImageBucketAdapter extends BaseAdapter implements Callback,OnScrollListener{

	Context context;
	Handler handler;
	BitmapMemoryCache cache;
	List<ImageBucket> buckets;
	ExecutorService taskService;

	int firstVisibleItem;
	int visibleItemCount;
	
	@SuppressWarnings("unchecked")
	public ImageBucketAdapter(Context context,List<?> buckets){
		this.context = context;
		this.buckets = (List<ImageBucket>) buckets;	
		this.handler = new Handler(this);
		
		cache = new BitmapMemoryCache(context);
		taskService = Executors.newFixedThreadPool(1);
	
		firstVisibleItem = -1;
		visibleItemCount = -1;
	}

	@Override
	public int getCount() {
		return buckets.size();
	}

	@Override
	public Object getItem(int position) {
		return buckets.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			Holder holder = new Holder();

			convertView = View.inflate(context, R.layout.item_albums, null);
			
			holder.iv = (ImageView) convertView.findViewById(R.id.image);
			holder.selected = (ImageView) convertView.findViewById(R.id.isselected);
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.count = (TextView) convertView.findViewById(R.id.count);
			convertView.setTag(holder);

			setItem(holder,(ImageBucket)getItem(position),position);
		} 
		else {
			setVisibleItemCount(convertView);
			Holder holder = (Holder) convertView.getTag();
			setItem(holder,(ImageBucket)getItem(position),position);
		}

		return convertView;
	}

	protected void setVisibleItemCount(View convertView){
		if(visibleItemCount == -1 
				&& convertView.getWidth() != 0 
				&& convertView.getHeight() != 0){
			DisplayMetrics dm = context.getResources().getDisplayMetrics();
			int columns = dm.widthPixels / convertView.getWidth();
			int rows = dm.heightPixels / convertView.getHeight();
			visibleItemCount = columns * (rows + 1);
		}
	}
	
	/**
	 * 设置每一项的内容
	 * @param holder
	 * @param imageBucket
	 */
	protected void setItem(Holder holder,ImageBucket imageBucket,int position){
		holder.name.setText(imageBucket.bucketName);
		holder.count.setText(String.valueOf(imageBucket.count));
		holder.selected.setVisibility(View.GONE);

		if(imageBucket.imageList == null || imageBucket.imageList.size() == 0){
			holder.iv.setImageBitmap(null);
			return;
		}

		ImageItem item = imageBucket.imageList.get(0);
		item.arg1 = position;
		holder.iv.setTag(item);
		displayBitmap(holder.iv, item);
	}

	protected void displayBitmap(ImageView iv,ImageItem item){
		String path = item.thumbnailPath;
		boolean isThumbPath = true;

		if(path == null || path.trim().length() == 0){
			path = item.imagePath;
			isThumbPath = false;				
		}
		if(path == null || path.trim().length() == 0){
			return;
		}

		Bitmap bitmap = cache.getBitmapFromCache(path);
		if(bitmap != null){
			iv.setImageBitmap(bitmap);
			return;
		}

		iv.setImageBitmap(null);
		loadBitmap(iv, isThumbPath, path, item);
	}

	private void loadBitmap(final ImageView iv, 
			final boolean isThumbPath, final String path,final ImageItem item){
		Runnable command = new Runnable() {
			public void run() {
				if(!isItemVisible(item)){
					return;
				}
				Bitmap thumb;
				if (isThumbPath) {
					thumb = BitmapFactory.decodeFile(path);
					if (thumb == null){
						thumb = ImageUtil.revisionImageSize(item.imagePath);						
					}
				} 
				else {
					thumb = ImageUtil.revisionImageSize(path);		
				}
				if (thumb == null) {
					return;//Note
				}

				cache.addBitmapToCache(path, thumb);
				final Bitmap bitmap = thumb;
				handler.post(new Runnable() {
					@Override
					public void run() {
						onImageLoaded(iv, bitmap, item.imagePath);
					}
				});
			}
		};
		
		taskService.submit(command);
	}

	private boolean isItemVisible(ImageItem item){
		if(firstVisibleItem == -1 || visibleItemCount == -1 )
			return true;
		return item.arg1 >= firstVisibleItem && item.arg1 <= (firstVisibleItem + visibleItemCount);
	}
	
	private void onImageLoaded(ImageView iv, Bitmap thumb,String url){
		if(iv == null || thumb == null)
			return;
		ImageItem imageItem = (ImageItem) iv.getTag();
		if (url != null && url.equals(imageItem.imagePath)) {
			iv.setImageBitmap(thumb);
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		return false;
	}

	public class Holder {
		public ImageView iv;
		public ImageView selected;
		public TextView name;
		public TextView count;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		this.firstVisibleItem = view.getFirstVisiblePosition();
		if(scrollState == SCROLL_STATE_IDLE){
			notifyDataSetChanged();
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		this.firstVisibleItem = firstVisibleItem;
	}
}
